package ru.ipo.dces.utils;

import ru.ipo.problemsapi.ExtendedProblem;
import javax.swing.*;
import javax.swing.text.html.HTMLDocument;
import java.awt.*;
import java.io.*;

public class UIUtils {
    private static ExtendedProblem problem;
    private static String resource;

    //TODO think of view customization and also about controlling its preferred size
    public static JComponent getDisplayComponent(ExtendedProblem p, String resourceName) {
        JComponent component;
        resource = resourceName;
        problem = p;
        String type = problem.getResourceType(resourceName);
        InputStream statement = problem.getReadStream(resourceName);

        if (type == null)
            type = "text/plain";

        //interpret statement depending on its extension
        if (type.equals("text/html"))
            component = createHtmlStatementComponent(statement);
        else if (type.startsWith("image/"))
            component = createImageStatementComponent(statement);
        else if (type.equals("application/rtf"))
            component = createRtfStatementComponent(statement);
        else if (type.equals("text/plain"))
            component = createTxtStatementComponent(statement);
        else
            return null;

        return component;
    }


    //statement components
    private static JComponent createHtmlStatementComponent(InputStream statement) {
        try {
            File baseDir = getTemporaryFolder();
            if (baseDir == null)
                return failedToShowComponent();
            if (!baseDir.mkdirs())
                throw new Exception("Не удалось создать каталог для временного хранения ресурсов");

            for (String resource : problem.listNames()) {
                File resourceDir = baseDir;
                String resourceFileName = resource;
                if (resource.contains("/")) {
                    String path = resource.substring(0, resource.lastIndexOf("/"));
                    resourceFileName = resource.substring(resource.lastIndexOf("/") + 1);
                    resourceDir = new File(resourceDir + "/" + path);
                    if (!resourceDir.mkdirs())
                        throw new Exception("Не удалось создать каталог для ресурса");
                    System.out.println(resourceDir.getAbsolutePath());
                    System.out.println(resourceFileName);
                }
                File temp = new File(resourceDir, resourceFileName);
                if (resource.equals("statement"))
                    System.err.println("here");
                FileSystemUtils.copyFileFromInputStream(problem.getReadStream(resource), temp);
            }

            JTextPane pane = new JTextPane();
            pane.setEditable(false);
            pane.setDisabledTextColor(Color.BLACK);
            pane.setFocusable(false);
            pane.setContentType("text/html; charset=" + new ExtendedProblem(problem).getEncoding(resource));

            //TODO try to rewrite document creation as in http://www.javaworld.com/javatips/jw-javatip109.html?page=1
            //TODO think of base URL with kio-problem protocol (cf. jar-jar protocol somewhere in KIO-API)
            pane.read(statement, "statement");

            HTMLDocument doc = (HTMLDocument)pane.getDocument();
            doc.setBase(baseDir.toURI().toURL());
            return new JScrollPane(pane);
        } catch (Exception e) {
            return UIUtils.failedToShowComponent();
        }
    }


    private static JComponent createImageStatementComponent(InputStream statement) {
        final String imageStream = FileSystemUtils.inputStreamToString(statement);
        final byte[] imageByteString = imageStream.getBytes();

        Image image;
        image = Toolkit.getDefaultToolkit().createImage(imageByteString);
        // Создание компонента с изображением
        JLabel imageComponent = new JLabel();
        Icon icon = new ImageIcon(image);
        imageComponent.setIcon(icon);
        return imageComponent;
    }


    private static JComponent createRtfStatementComponent(InputStream statement) {
        return createHtmlStatementComponent(statement);
    }


    private static JComponent createTxtStatementComponent(InputStream statement) {
        JTextArea textComponent = new JTextArea(FileSystemUtils.inputStreamToString(statement));
        textComponent.setEditable(false);
        return new JScrollPane(textComponent);
    }

    private static File getTemporaryFolder() {
        try {
            File tmp = File.createTempFile("problem", "_tmp");
            if (!tmp.delete())
                return null;
            return tmp;
        } catch (IOException e) {
            return null;
        }
    }

    private static JLabel failedToShowComponent() {
        return new JLabel("Ошибка. Не удалось отобразить компонент.");
    }

}